Simpler case


In [167]:
def bracketBalancingSimpler(string: String): Boolean =  {
    def bracket(s: String, openCount: Int): Boolean = {
        if (s.isEmpty)
            openCount == 0
        else if (s.head == ')')
            bracket(s.tail, openCount + 1)
        else if (s.head == '(')
            bracket(s.tail, openCount - 1)
        else
            bracket(s.tail, openCount)
    }

    bracket(string, 0)
}


defined function bracketBalancingSimpler

In [172]:
val testCases = Map(
    "a(" -> false,
    "a()b(())cc()d" -> true,
    "a()" -> true,
    "a(())" -> true,
    "a()b(())c()" -> true
)

testCases.foreach { case(test, expected) =>
    assert(bracketBalancingSimpler(test) == expected)
}


testCases: Map[String, Boolean] = Map(
  "a()b(())cc()d" -> true,
  "a(())" -> true,
  "a()" -> true,
  "a()b(())c()" -> true,
  "a(" -> false
)

General case


In [169]:
import scala.collection.immutable.Stack

def bracketBalancing(string: String): Boolean = {
    val brackets = Map(')' -> '(', '}' -> '{', ']' -> '[')
    
    def bracket(s: String, stack: Stack[Char]): Boolean = {
        if (s.isEmpty)
            stack.isEmpty
        else if (brackets.values.toVector.contains(s.head))
            bracket(s.tail, stack.push(s.head))
        else if (brackets.keys.toVector.contains(s.head)) {
            if (!stack.isEmpty && stack.head == brackets(s.head))
                bracket(s.tail, stack.pop)
            else
                false
        }
        else
            bracket(s.tail, stack)
    }

    bracket(string, Stack())
}


import scala.collection.immutable.Stack
defined function bracketBalancing

In [171]:
val testCases = Map(
    "}" -> false,
    "{}{()" -> false,
    "a({})" -> true,
    "{{{}}}" -> true,
    "[[(]]" -> false,
    "[[)]]" -> false,
    "[[]][" -> false,
    "[[]]}" -> false,
    "()()[]{" -> false,
    "()()[]" -> true,
    "()()[]((((()))))[[[]]][[{{(([[]]))}}]]" -> true
)

testCases.foreach { case(test, expected) =>
    assert(bracketBalancing(test) == expected)
}


testCases: Map[String, Boolean] = Map(
  "[[]]}" -> false,
  "()()[]((((()))))[[[]]][[{{(([[]]))}}]]" -> true,
  "()()[]{" -> false,
  "{{{}}}" -> true,
  "}" -> false,
  "()()[]" -> true,
  "[[)]]" -> false,
  "[[(]]" -> false,
  "[[]][" -> false,
  "a({})" -> true,
  "{}{()" -> false
)

In [ ]: